package com.kktestspb.demo.aspect;


import com.kktestspb.demo.polo.Visitor;
import com.kktestspb.demo.services.VisitorServices;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;


@Aspect
@Component
public class MyAspect {

    @Autowired
    VisitorServices visitorServices;

    @Autowired
    Visitor visitor;
    private final static Logger logger= LoggerFactory.getLogger(MyAspect.class);
    @Pointcut("execution(public * com.kktestspb.demo.controller.PcController.*(..))")
    public void PcController(){}

    @Pointcut("execution(public * com.kktestspb.demo.controller.UserController.*(..))")
    public void UserController(){}

    @Before(value = "PcController()")
    public void beforePc(JoinPoint jp)
    {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //请求的IP
        String ip = request.getRemoteAddr();
        logger.info("客户机IP地址为："+ip+"访问服务器"+jp.getSignature().getName()+"方法。");
        logger.info("*********开始执行***进入"+jp.getSignature().getName()+"方法****************************");
        insertVisitor(ip,jp.getSignature().getName());

    }

    @Before(value = "UserController()")
    public void beforeUser(JoinPoint jp)
    {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        //请求的IP
        String ip = request.getRemoteAddr();
        logger.info("客户机IP地址为："+ip+"访问服务器"+jp.getSignature().getName()+"方法。");
        logger.info("*********开始执行***进入"+jp.getSignature().getName()+"方法****************************");
        insertVisitor(ip,jp.getSignature().getName());
    }


    /**
     * add by kk 20190901 21:17
     * 加入来访者记录表
     * @param ip
     * @param sMethod
     */
    private void insertVisitor(String ip,String sMethod){
        visitor.setvIpAddress(ip);
        visitor.setvVisitDate(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
        visitor.setvVisitMethod(sMethod);
        visitorServices.addVisitor(visitor);
    }



}
